package com.zhang.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.zhang.Boot;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * spring整合mybatis的配置类，用配置类来取代配置文件
 */
@Configuration //表明这是配置类，包含@Comment、会被加入到spring组件
@ComponentScan(basePackageClasses = Boot.class) //扫描MainStart的包及其子包的spring组件
@MapperScan("com.zhang.mapper") //将com.zhang.mapper下的接口生成实现类
@EnableTransactionManagement //自动开启事务
public class MybatisConfig {

    /**
     * 配置Alibaba的数据源druid，在以前的mybatis的配置核心文件里面进行配置
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource druid = new DruidDataSource();
        druid.setDriverClassName("com.mysql.jdbc.Driver");
        druid.setUrl("jdbc:mysql://localhost:3306/db_lovo?useSSl=false&characterEncoding=utf8&useUnicode=false&allowMultiQueries=true");
        druid.setUsername("root");
        druid.setPassword("123456");
        druid.setMaxActive(100);
        druid.setMinIdle(10);
        druid.setMaxWait(1000);
        return druid;
    }

    @Bean
    public SqlSessionFactoryBean factoryBean() {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //下面这两行代码组合起来就是我们以前写的mybatis配置文件
        //以前是SqlSessionFactoryBuild的build方法加载配置文件帮我们产生SqlSessionFactory
        //现在是往SqlSessionFactoryBean设置需要的配置产生SqlSessionFactoryBean;
        factoryBean.setDataSource(dataSource());
        factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        return factoryBean;
    }

    @Bean
    public TransactionManager transactionManager() {
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(dataSource());
        return manager;
    }

}